"""
    电机
"""
import time

from fastapi import APIRouter, FastAPI, HTTPException
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from periphery import PWM


class Motor:
    def __init__(self, chipa, ma, chipb, mb):
        # 打开PWM芯片
        self.pwma = PWM(chipa, ma)
        self.pwmb = PWM(chipb, mb)

        # 设置频率
        self.pwma.frequency = 1000
        self.pwmb.frequency = 1000

        # 设置极性
        self.pwma.polarity = "inversed"
        self.pwmb.polarity = "inversed"

        # 设置占空比为0
        self.pwma.duty_cycle = 0
        self.pwmb.duty_cycle = 0

        # 启用PWM
        self.pwma.enable()
        self.pwmb.enable()

    def write(self, speed):
        if speed >= 0:
            self.pwma.duty_cycle = abs(speed)
            self.pwmb.duty_cycle = 0
        else:
            self.pwma.duty_cycle = 0
            self.pwmb.duty_cycle = abs(speed)

    def deinit(self):

        # 关闭PWM
        self.pwma.disable()
        self.pwmb.disable()
        self.pwma.close()
        self.pwmb.close()


router = APIRouter(
    prefix='/motor',
    tags=['motor']
)


class SchemaIn(BaseModel):
    angle: float = Field(..., description="电机转动的角度(-1到1)")


@router.post("/", summary='电机控制')
def motor_control(data: SchemaIn):
    angle = data.angle

    motor = Motor(0, 0, 1, 0)

    # 先停止，再转
    motor.write(0)
    if angle:
        motor.write(angle)
    else:
        motor.deinit()

    return {'message': '电机控制成功'}
